<?php

namespace Home\Controller;
use Think\Controller;

/**
* 支付类控制器
* @param type $param['transaction_id'] 订单id
* @autho cheng
*/
class PayController extends BaseController {

    /**
     * 支付回调接口（成功调用）
     * @param type $param['transaction_id'] 订单id
     * @param type $param['channel_type'] 支付渠道
     * @again quyang 2017-1-18
     * @autho cheng
     */
    public function payCallBack() {
        $param = json_decode(file_get_contents("php://input"), true);
        if (empty($param['transaction_id']) || empty($param['channel_type'])) {
            $this->param_error();
        }
        //1. 根据订单号，查询订单信息(包含商品信息)
        $orderInfo = D('Home/Order')->getOrderProduct($param['transaction_id']);
        empty($orderInfo) && $this->output(0);
        //2. 据订单商品信息判断，如果为1，则是注册套餐，如果是2则为短信充值
        //首先修改订单状态
	    $status = D('Home/Order')->saveOrderStatus($orderInfo['F_ORDER_ID']);
        if ($status == FALSE) { //说明已付款过
            echo 'success';exit();
        }
        //3. 如果商品类型为1 注册套餐 (a.修改订单状态，b.修改审核状态,3.添加短信套餐给用户,4.生成协议信息)
        if (1 == $orderInfo['F_PRODUCT_TYPE'] || 3 == $orderInfo['F_PRODUCT_TYPE']){

            //添加账户有效期  201-2-17
            $termOfValidity = '';
            //添加短信套餐给用户
            if (3 == $orderInfo['F_PRODUCT_TYPE'] ){
                $count = $orderInfo['F_MESSAGE_NUM'] ? $orderInfo['F_MESSAGE_NUM'] : 0;
                $termOfValidity = date("YmdHis",strtotime("+1 year"));
            }else if(1 == $orderInfo['F_PRODUCT_TYPE']){
                $count = 0;
                $termOfValidity = date("YmdHis",strtotime("+10 day"));
            }

            //修改审核状态
            D('Home/User')->saveStatus($orderInfo['F_USER_ID'],$termOfValidity);
            D('Home/User')->where(array('f_user_id'=>$orderInfo['F_USER_ID']))->setInc('f_buy_count', $count);
            //生成协议信息（1查询协议信息，2查询用户信息用于替换模板,3插入新生成的合同到tp_station_contract表）
            $template = D('Home/ContractTemplate')->getTemplate(); //查询协议信息
            $user_info = D('Home/User')->getUserInfo($orderInfo['F_USER_ID']); //查询用户信息用于替换模板
            if (!empty($template) && !empty($user_info)) {
                $contents = D('Home/ContractTemplate')->replaceWords($template['f_contract_content'], $user_info);
            }
            //插入新生成的合同到tp_station_contract表
            $c_map['f_user_id'] = $orderInfo['F_USER_ID'];
            $c_map['f_contract_url'] = '';
            $c_map['f_state'] = 1;
            $c_map['f_contract_text'] = $contents;
            D('Home/User')->save($c_map);
            $log_map['f_msg_num'] = $orderInfo['F_MESSAGE_NUM']; //f_msg_num充值数量
        // 4. 如果商品类型为2 短信充值 (a.修改订单状态(上面已统一修改)，b.更新用户短信数量)
        } elseif (2 == $orderInfo['F_PRODUCT_TYPE']) {
            //处理短信充值异常
            $actual_count = $this->exceptionHandling($param['transaction_fee'], $orderInfo);
            //更新用户短信数量
            $msg_count = $actual_count ? $actual_count : $orderInfo['F_COUNT'];
            D('Home/User')->where(array('f_user_id'=>$orderInfo['F_USER_ID']))->setInc('f_buy_count', $msg_count);
            $log_map['f_msg_num'] = $msg_count;

            //查询是否有上级代理  有则返现
            $User = new \Home\Model\UserModel();
            $user_info = $User->getUserInfo( $orderInfo['F_USER_ID'] );
            if ( $user_info['f_proxy_id'] !='' && $user_info['f_proxy_id'] != 0 )
            {
                $Money = new \Home\Model\ReturnMoneyModel();

                //查询是否存在相同的订单ID  防止重复回调
                $order_info = $Money->queryOrder( $orderInfo['F_USER_ID'] , $param['transaction_id'] );

                //不存在则写入log
                if ( !$order_info )
                {
                    //每条返现2分  处理金额
                    $return_money =  $msg_count*0.02;

                    //写入返现log表
                    $log = $Money->addRechargeLog( $orderInfo['F_USER_ID'] , $user_info['f_proxy_id'] , $msg_count , $return_money , $param['transaction_id'] );

                    if ( $log )
                    {

                        //写入用户总返现金额记录表
                        $Money_info = new \Home\Model\ProxyMoneyInfoModel();

                        //查询是否有余额
                        $proxy = $Money_info->queryProxy( $user_info['f_proxy_id'] );

                        //存在记录则修改
                        if ( is_array( $proxy ) && count( $proxy ) > 0 )
                        {
                            $Money_info->updateProxyDetails( $user_info['f_proxy_id'] , $return_money );
                        }
                        else
                        {
                            $Money_info->addProxyDetails( $user_info['f_proxy_id'] , $return_money );
                        }

                    }
                }
            }

            //根据用户充值记录更改通知表通知状态
            $App_Notice = new \Home\Server\AppNoticeServer();
            //推送类型为余额不足
            $App_where = "`f_receive_id`={$orderInfo['F_USER_ID']} AND `f_push_type` BETWEEN 1 AND 3";
            $App_map['f_push_type'] = '-1';

            //查询用户通知是否存在
            $App_user = $App_Notice->queryNoticeExistence( $App_where );
            if ($App_user){
                $App_Notice->updateAppNotice( $App_where , $App_map );
            }
            
        }
        //插入数据到充值短信信息记录表tp_recharge_msg_log
        $log_map['f_order_id'] = $orderInfo['F_ORDER_ID'];
        $log_map['f_user_id'] = $orderInfo['F_USER_ID'];
        $log_map['f_pay_time'] = date('YmdHis');
        $log_map['f_opt_IP'] = $_SERVER["REMOTE_ADDR"];
        $log_map['f_opt_id'] = $orderInfo['F_USER_ID'];
        $log_map['f_pay_status'] = 1;
        D('Home/RechargeMsgLog')->addRechargeMsgLog($log_map);

        echo 'success';
    }
    
    /**
     * 短信充值时：BeeCloud返回的总价和订单中的不匹配的异常处理
     * @param type $transaction_fee BeeCloud返回的总价
     * @param type $orderInfo 商品信息
     * @author cheng
     */
    public function exceptionHandling($transaction_fee, $orderInfo) {
        //短信充值
        $count = '';
        if ($orderInfo['F_PRODUCT_ID'] == 2 && $transaction_fee != $orderInfo['F_AMOUNT']) {
            //先记录到短信充值异常日志表tp_recharge_msg_exc_log
            $e_map['f_order_id'] = $orderInfo['F_ORDER_ID'];
            $e_map['f_user_id'] = $orderInfo['F_USER_ID'];
            $e_map['f_count'] = $orderInfo['F_COUNT'];
            $e_map['f_order_amount'] = $orderInfo['F_AMOUNT']; //订单中商品总价，单位分,下一步会修改掉订单里的总价格
            $e_map['f_actual_amount'] = $transaction_fee; //客户实际支付总价，单位分
            $e_map['f_create_time'] = date('YmdHis');
            D('RechargeMsgExcLog')->add($e_map);
            //修改订单表和订单商品表
            D('Home/Order')->where(array('F_ORDER_ID' => $orderInfo['F_ORDER_ID']))->save(array('F_AMOUNT' => $transaction_fee)); //修改t_order表中的总价
            D('Home/OrderProduct')->where(array('F_ORDER_PRODUCT_ID' => $orderInfo['F_ORDER_PRODUCT_ID']))->save(array('F_AMOUNT' => $transaction_fee)); //修改t_order_product表中的总价 
            //计算应该充值的条数
            $orderInfo['F_PRODUCT_PRICE'] && $count = round($transaction_fee/$orderInfo['F_PRODUCT_PRICE']);
        }
        return $count;
    }

    /**
     * 在线寄包裹: 微信支付成功回调
     * @author luwushuang
     */
    public function mailPayCallPack() {
        /**
         * http类型为 Application/json, 非XMLHttpRequest的application/x-www-form-urlencoded, $_POST方式是不能获取到的，
         * APP ID和Master Secret可以在https://beecloud.cn平台登录后获取
         *
         * 备注：secret是一个非常重要的数据，请您必须小心谨慎的确保此数据保存在足够安全的地方。
         *      您从BeeCloud官方获得此数据的同时，即表明您保证不会被用于非法用途和不会在没有得到您授权的情况下被盗用，
         *      一旦因此数据保管不善而导致的经济损失及法律责任，均由您独自承担。
         */

        //$file = file_put_contents("./Public/log_".time().".txt",1,FILE_APPEND);
        //header('Content-type:application/json');
        $appId = "bbc77d17-58d3-4328-9410-9f94cf616fb1";
        $masterSecret = "f9aa1dfa-d66e-41ef-8769-d9c2bf2f2639";
        $jsonStr = file_get_contents("php://input");
        $msg = json_decode($jsonStr);

        /*$msg =  '{"channelType":"WX","channel_transaction_id":"4006732001201707140674793254","tradeSuccess":true,"id":"301063b9-f8ac-4531-ba09-66f986cec3fe","channel_type":"WX","app_id":"bbc77d17-58d3-4328-9410-9f94cf616fb1","retryCounter":8,"transaction_id":"201707140950101499997010","retry_counter":0,"transaction_fee":1,"sub_channel_type":"WX_JSAPI","optional":{"acid":"8","uniacid":"8","openid":"oT3R2xEqaYGH1cFEzu0TsaXLdHgg","out_trade_no":"201707140950101499997010","orderid":"76"},"transaction_type":"PAY","notify_url":"http://api.test.baimixu.cn/index.php?reqUrl=Pay.mailPayCallPack","transactionId":"201707140950101499997010","transactionType":"PAY","transactionFee":1,"notifyUrl":"http://api.test.baimixu.cn/index.php?reqUrl=Pay.mailPayCallPack","messageDetail":{"transaction_id":"4006732001201707140674793254","nonce_str":"201707140950101499997010","bank_type":"CFT","openid":"o5rmPswsw3JHzVrdTTkythKMeVHI","fee_type":"CNY","mch_id":"1251241101","cash_fee":"1","out_trade_no":"201707140950101499997010","transactionFee":1,"tradeSuccess":true,"appid":"wx0670da15858dd9c6","total_fee":"1","trade_type":"JSAPI","result_code":"SUCCESS","time_end":"20170714095027","is_subscribe":"Y","return_code":"SUCCESS"},"message_detail":{"transaction_id":"4006732001201707140674793254","nonce_str":"201707140950101499997010","bank_type":"CFT","openid":"o5rmPswsw3JHzVrdTTkythKMeVHI","fee_type":"CNY","mch_id":"1251241101","cash_fee":"1","out_trade_no":"201707140950101499997010","transactionFee":1,"tradeSuccess":true,"appid":"wx0670da15858dd9c6","total_fee":"1","trade_type":"JSAPI","result_code":"SUCCESS","time_end":"20170714095027","is_subscribe":"Y","return_code":"SUCCESS"},"trade_success":true,"signature":"4907a1a750646a869698ea71c6916233","sign":"897cbdd30d21ecfc8d11d6a295eb6159","signAll":"57e1c47d377fa478c84e6272fea57a38","timestamp":1499997480000}'; */

        //print_r($msg);exit;

        //$msg = json_decode($jsonStr);
        //$file = file_put_contents("./Public/log_".time().".txt",$msg,FILE_APPEND);

        //第一步:验证签名
        //现修正如下：app_id + transaction_id + transaction_type + channel_type + transaction_fee + master_secret

        $sign = md5($appId . $msg->transaction_id . $msg->transaction_type . $msg->channel_type . $msg->transaction_fee.$masterSecret);
        if ($sign != $msg->signature) {
            // 签名不正确
            exit();
        }
        //第四步:处理业务逻辑和返回
        /*
         * 推送支付的结果
         */
        if($msg->transaction_type == "PAY") {
            //付款信息
            //支付状态是否变为支付成功,true代表成功
            $status = $msg->trade_success;
            //message_detail 参考文档
            //channel_type 微信/支付宝/银联/快钱/京东/百度/易宝/PAYPAL/BC
            switch ($msg->channel_type) {
                case "WX":
                    if($status == 1) {
                        $out_trade_no = $msg->messageDetail->out_trade_no;
                        $data = M('tp_send_list')->where("orderNum = '{$out_trade_no}'")->save(['orderState'=>1, 'paytime' => time()]);
                    }
                    break;
                case "ALI":
                    break;
                case "UN":
                    break;
                case "KUAIQIAN":
                    break;
                case "JD":
                    break;
                case "BD":
                    break;
                case "YEE":
                    break;
                case "PAYPAL":
                    break;
                case "BC":
                    //BC订阅收费
                    if($msg->sub_channel_type == 'BC_SUBSCRIPTION'){
                    }
                    //BC代扣
                    if($msg->sub_channel_type == 'BC_CARD_CHARGE'){
                    }
                    break;
            }
        } else if ($msg->transaction_type == "REFUND") { //退款的结果

        }
        //print_r($msg);
        //处理消息成功,不需要持续通知此消息返回success
        echo 'success';
    }

}
